package com.lizongbo.seotijian.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.DeflaterInputStream;
import java.util.zip.GZIPInputStream;

public abstract class HttpUtil {
	private static final String ALLOW_HTTP_REQ_HEADERS[] = new String[] {
			"User-Agent", "Accept", "Accept-Language", "Accept-Encoding",
			"Accept-Charset", "Cache-Control", "Referer" };
	private static final Map<String, String> HEADERS = new HashMap<String, String>();
	static {
		Arrays.sort(ALLOW_HTTP_REQ_HEADERS);
		HEADERS
				.put(
						"User-Agent",
						"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
		HEADERS
				.put("Accept",
						"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		HEADERS.put("Accept-Language", "zh-cn,zh;q=0.5");
		HEADERS.put("Accept-Encoding", "gzip,deflate");
		HEADERS.put("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
	}

	public static String httpGet(String urlStr) throws Exception {
		return httpGet(urlStr, "UTF-8");
	}

	public static String httpGet(String urlStr, String encoding)
			throws Exception {
		return httpGet(urlStr, encoding, null);
	}

	/**
	 * 用指定编码下载网页内容
	 * 
	 * @param urlStr
	 * @param encoding
	 * @return
	 * @throws Exception
	 */
	public static String httpGet(String urlStr, String encoding,
			java.util.Map<String, String> headers) throws Exception {
		URL url = new URL(urlStr);
		HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
		fillRequestProperty(urlc, headers);
		urlc.setConnectTimeout(5000);
		urlc.connect();
		StringBuilder sb = new StringBuilder(64);
		InputStream is = urlc.getInputStream();
		if ("gzip".equalsIgnoreCase(urlc.getContentEncoding())) {
			System.out.println("uses gzip response:" + urlc.getContentLength());
			is = new GZIPInputStream(is);
		} else if ("deflate".equalsIgnoreCase(urlc.getContentEncoding())) {
			is = new DeflaterInputStream(is);
		}
		BufferedReader in = new BufferedReader(new InputStreamReader(is,
				encoding));
		String line;
		while ((line = in.readLine()) != null) {
			sb.append(line).append('\n');
		}
		in.close();
		System.out.println(urlStr);
		return sb.toString().trim();
	}

	public static String httpPost(String urlStr, String param) throws Exception {
		return httpPost(urlStr, param, null);
	}

	public static String httpPost(String urlStr, String param, String referer)
			throws Exception {
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Referer", referer);
		return httpPOST(urlStr, param, referer, "UTF-8", headers);
	}

	public static String httpPOST(String urlStr, String param, String referer,
			String encoding, Map<String, String> headers) throws Exception {
		StringBuilder sb = new StringBuilder(64);
		try {
			URL url = new URL(urlStr);
			HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
			urlc.setDoInput(true);
			urlc.setDoOutput(true);
			urlc.setRequestMethod("POST");
			fillRequestProperty(urlc, headers);
			urlc.getOutputStream().write(param.getBytes());
			urlc.getOutputStream().flush();
			urlc.getOutputStream().close();
			InputStream is = urlc.getInputStream();
			if ("gzip"
					.equalsIgnoreCase(urlc.getHeaderField("Content-Encoding"))) {
				is = new GZIPInputStream(is);
			} else if ("deflate".equalsIgnoreCase(urlc
					.getHeaderField("Content-Encoding"))) {
				is = new DeflaterInputStream(is);
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(is,
					encoding));
			String line;
			while ((line = in.readLine()) != null) {
				sb.append(line).append('\n');
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(urlStr + "?" + param);
		return sb.toString();
	}

	private static void fillRequestProperty(HttpURLConnection urlc,
			java.util.Map<String, String> headers) {
		if (urlc != null) {
			if (headers == null) {
				headers = HEADERS;
			}
			for (Map.Entry<String, String> e : headers.entrySet()) {
				if (e.getValue() != null
						&& Arrays.binarySearch(ALLOW_HTTP_REQ_HEADERS, e
								.getKey()) >= 0) {
					urlc.setRequestProperty(e.getKey(), e.getValue());
				}
			}
		}
	}

	public static void main(String[] args) throws Exception {

		System.out.println(HttpUtil.httpGet("http://seotijian.com/"));
	}
}
